// src/utils/rsa-util.js
import JSEncrypt from 'jsencrypt'

class RsaUtil {
  constructor(publicKey = '', privateKey = '') {
    this.publicKey = publicKey
    this.privateKey = privateKey
    this.encryptor = new JSEncrypt()
    if (publicKey) this.encryptor.setPublicKey(publicKey)
    if (privateKey) this.encryptor.setPrivateKey(privateKey)
  }

  setPublicKey(publicKey) {
    this.publicKey = publicKey
    this.encryptor.setPublicKey(publicKey)
  }

  setPrivateKey(privateKey) {
    this.privateKey = privateKey
    this.encryptor.setPrivateKey(privateKey)
  }

  encrypt(plainText) {
    const cipher = this.encryptor.encrypt(plainText)
    if (!cipher) throw new Error('RSA 加密失败，请检查公钥或内容长度')
    return cipher
  }

  decrypt(cipherText) {
    const plain = this.encryptor.decrypt(cipherText)
    if (plain === false) throw new Error('RSA 解密失败，请检查私钥或密文')
    return plain
  }

  // 私钥签名
  sign(content) {
    const signature = this.encryptor.sign(content, CryptoJS.SHA256, 'sha256')
    if (!signature) throw new Error('RSA 签名失败')
    return signature
  }

  // 公钥验签
  verify(content, signature) {
    return this.encryptor.verify(content, signature, CryptoJS.SHA256)
  }

  /**
   * 静态方法：生成一对公私钥
   * @param {number} bits 密钥长度，默认 512
   * @returns {object} { publicKey, privateKey }
   */
  static generateKeyPair(bits = 512) {
    const key = new JSEncrypt({ default_key_size: bits })
    return {
      publicKey: key.getPublicKey(),
      privateKey: key.getPrivateKey()
    }
  }
}

export default RsaUtil
